package com.lin.csdn.controller;

import com.lin.csdn.service.impl.BlogService;
import com.lin.csdn.utils.BlogJsonUtil;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/BlogServlet")
public class BlogServlet extends HttpServlet{
    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     *
     * 0:根据领域获取博客的数据 DomainGetBlog
     * 1:根据用户来获取博客 NameGetBlog
     * 2:复杂搜索 Seek
     * 3:点赞排序 ThumbOrder
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //建立功能代表的code调用
        String DomainGetBlog="0";//调用使用后台查询博客的方法
        String NameGetBlog="1";//调用使用用户名来查询博客的方法
        String Seek="2";//调用复杂搜索的方法
        String ThumbOrder="3";//调用使用点赞数排序的方法
        //获取req数据
        String domain=req.getParameter("domain");
        String userName=req.getParameter("loginName");
        String code=req.getParameter("code");

        List<Object> data = null;
        BlogService blogService = new BlogService();
        PrintWriter writer = resp.getWriter(); //响应流
        BlogJsonUtil jsonUtil=new BlogJsonUtil();

        //根据需求调用各自的方法
        if(code.equals(DomainGetBlog)) {
            String Page=req.getParameter("currentPage");
            int currentPage=Integer.parseInt(Page);
            //设置每次查询的条数
            int pageSize=10;
            int beginIndex = (currentPage - 1) * pageSize;
            data = blogService.blog(domain,beginIndex,pageSize);
        }
        else if(code.equals(NameGetBlog)){
            String Page=req.getParameter("currentPage");
            int currentPage=Integer.parseInt(Page);
            //设置每次查询的条数
            int pageSize=10;
            int beginIndex = (currentPage - 1) * pageSize;
            data=blogService.ownBlog(userName,beginIndex,pageSize);
        }
        else if(code.equals(Seek)){
            String target=req.getParameter("field");
            data=blogService.seek(target);
        }
        else if(code.equals(ThumbOrder)){
            data=blogService.thumbOrder();
        }
        assert data != null;
        JSONArray array=jsonUtil.blogJson(data);
        writer.print(array);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
